home *** CD-ROM | disk | FTP | other *** search
- Path: news.umbc.edu!not-for-mail
- From: schlein@umbc.edu (Jonas J. Schlein)
- Newsgroups: comp.lang.c
- Subject: Re: Question about sscanf
- Date: 10 Feb 1996 21:46:04 -0500
- Organization: University of Maryland Baltimore County
- Message-ID: <4fjl9c$51f@umbc9.umbc.edu>
- References: <4fe1oq$kuf@zippy.cais.net>
- NNTP-Posting-Host: umbc9.umbc.edu
- NNTP-Posting-User: schlein
-
- USAID <usaid@cais.cais.com> wrote:
- |> Here is a fragment of code that I'm having a problem with. The program
- |> is bombing on the line containing the call to sscanf. It assigns to the
- |> first variable fine, but blows up on the second one. I have no idea
- |> what's wrong.
-
- One thing you'll need is:
-
- #include <stdio.h>
-
- |> int formatFile(void)
- |> {
- |> int i;
- |> char line[MAX_LINE_LEN + 1];
-
- MAX_LINE_LEN has not been defined anywhere in your program.
-
- |> char *name;
- |> char *value;
- |> char *val[MAXREGIONS];
-
- Neither has MAXREGIONS.
-
- |> char *delimiter = ", ";
- |> FILE *ifp, *ofp;
- |>
- |> /* open input and output files */
- |> ifp = fopen("/opt/basis/tcs/formdata/test.txt", "r");
- |> ofp = fopen("/opt/basis/tcs/formdata/import.txt", "w");
- |> if ((ifp == NULL) || (ofp == NULL))
- |> return (0);
- |>
- |> while (fgetline(ifp, line, MAX_LINE_LEN) != -1)
-
- In ANSI C there is no such function called fgetline(). I would change this
- to:
-
- while (fgets (line, MAX_LINE_LEN, ifp) != NULL)
- |> {
- |> /* store the name and value in variables */
- |> if (sscanf(line, "%s %s", name, value) != 2)
-
- Well there ya go! Expecting C to provide magic storage for variables
- will always get you in trouble. Pointers point to things that you
- make them point to. You have omitted this step and as such as writing
- to an undefined region of memory. To correct the problem you will need to
- either have a char array for these variables of appropriate length or
- dynamically allocate an acceptable block of memory before the sscanf() call.
- See the FAQ for information on scanf() related functions and malloc()
- usage.
-
- |> {
- |> printf("Bad input from sscanf\n");
- |> return (0);
- |> }
- |> .
- |> .
- |> .
- |> }
- |> }
- --
- "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
-
- Jonas J. Schlein (schlein@gl.umbc.edu)
-